<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="6">
        <el-input placeholder="请输入咨询师姓名" clearable v-model="queryForm.name" />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          <el-tag :type="row.gender === 1 ? 'primary' : 'success'">
            {{ row.gender === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="level" label="级别" width="120">
        <template #default="{ row }">
          <el-tag :type="getLevelType(row.level)">
            {{ getLevelLabel(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="certificate" label="证书编号" width="150" />

      <el-table-column prop="is_recommend" label="推荐状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_recommend === 1 ? 'success' : 'info'">
            {{ row.is_recommend === 1 ? '已推荐' : '未推荐' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)" />
          <el-button
            :type="row.is_recommend === 1 ? 'warning' : 'success'"
            size="small"
            :icon="Star"
            @click="handleRecommend(row)"
          />
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="queryForm.pagenum"
      v-model:page-size="queryForm.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :form="currentForm"
    @success="handleSuccess"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus, Edit, Delete, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog.vue'
import counselorApi from '@/api/counselor'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentForm = ref({
  user_id: 0,
  name: '',
  mobile: '',
  email: '',
  gender: '',
  tags: [],
  is_recommend: 0,
  certificate: '',
  level: ''
})
const total = ref(0)
const queryForm = ref({
  name: '',
  pagenum: 1,
  pageSize: 10
})

const tableData = ref([])

// 获取级别标签类型
const getLevelType = (level) => {
  const types = {
    1: 'info',
    2: 'warning',
    3: 'success'
  }
  return types[level] || 'info'
}

// 获取级别标签文本
const getLevelLabel = (level) => {
  const labels = {
    1: '一级咨询师',
    2: '二级咨询师',
    3: '三级咨询师'
  }
  return labels[level] || '未知级别'
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const { data } = await counselorApi.getCounselor(queryForm.value)
    if (data) {
      if (Array.isArray(data)) {
        tableData.value = data
        total.value = data.length
      } else {
        ElMessage.error('获取咨询师列表失败')
      }
    } else {
      ElMessage.error(data?.message || '获取咨询师列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryForm.value.pagenum = 1
  getList()
}

// 新增
const handleAdd = () => {
  currentForm.value = {
    user_id: 0,
    name: '',
    mobile: '',
    email: '',
    gender: '',
    tags: [],
    is_recommend: 0,
    certificate: '',
    level: ''
  }
  dialogTitle.value = '新增咨询师'
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    const { data } = await counselorApi.getCounselor({}, row.user_id)
    if (data) {
      currentForm.value = data
      dialogTitle.value = '编辑咨询师'
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取咨询师详情失败:', error)
    ElMessage.error('获取咨询师详情失败')
  }
}

// 推荐/取消推荐
const handleRecommend = async (row) => {
  try {
    const newStatus = row.is_recommend === 1 ? 0 : 1
    const { data } = await counselorApi.updateCounselor(row.user_id, {
      is_recommend: newStatus
    })
    if (data) {
      ElMessage.success(newStatus === 1 ? '已设为推荐' : '已取消推荐')
      getList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该咨询师?', '提示', {
      type: 'warning'
    })
    const { data } = await counselorApi.deleteCounselor(row.user_id)
    if (data) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页
const handleSizeChange = (size) => {
  queryForm.value.pagenum = 1
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryForm.value.pagenum = page
  getList()
}

// 表单提交成功
const handleSuccess = () => {
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.header {
  padding: 16px;
  box-sizing: border-box;
}

:deep(.el-pagination) {
  margin-top: 16px;
  justify-content: center;
}

.el-tag {
  margin: 0 4px;
  &:first-child {
    margin-left: 0;
  }
}

.el-select {
  width: 100%;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
  }
}
</style>
